package server

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"
	"time"

	config "gitcode.com/happy-mj/happy-config"
	_ "github.com/go-sql-driver/mysql"
	"github.com/mark3labs/mcp-go/mcp"
	"github.com/mark3labs/mcp-go/server"
	"github.com/toon-format/toon-go"
)

// SaleRecord 对应视图 happy.medicine_sale_summary 的结构
type SaleRecord struct {
	StoreName string  `json:"store_name"`
	Location  string  `json:"location"`
	SaleTotal float64 `json:"sale_total"`
	Medicine  string  `json:"medicine"`
	City      string  `json:"city"`
	District  string  `json:"district"`
}

func SalesServer() *server.StreamableHTTPServer {
	// 1. 初始化 MCP Server
	s := server.NewMCPServer(
		"query_sales_data",
		"1.0.0",
	)

	// 2. 连接数据库
	dsn := os.Getenv("MYSQL_DSN")
	if dsn == "" {
		dsn = config.Cfg.MySQL.DSN
	}

	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("Failed to open mysql: %v", err)
	}

	if err := db.Ping(); err != nil {
		log.Fatalf("Failed to connect to mysql: %v", err)
	}

	// 3. 注册工具
	tool := mcp.NewTool("query_sales_data",
		mcp.WithDescription("查询药品销售明细。支持按城市筛选，按销量排序。"),
		mcp.WithString("city", mcp.Description("城市名称，如 '西安市'")),
		mcp.WithString("sort_by", mcp.Description("排序字段: sale_total 或 sale_date")),
		mcp.WithString("order", mcp.Description("排序方式: ASC 或 DESC")),
		mcp.WithNumber("limit", mcp.Description("返回记录数量限制")),
	)

	s.AddTool(tool, func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
		// --- 修复 1: Arguments 类型断言 ---
		// 在新版中 Arguments 是 any 类型，需要断言为 map[string]interface{}
		args, ok := request.Params.Arguments.(map[string]interface{})
		if !ok {
			// 如果没有参数或参数格式不对，给一个空的 map 防止 panic
			args = make(map[string]interface{})
		}

		// 提取参数 (注意类型断言)
		city, _ := args["city"].(string)
		sortBy, _ := args["sort_by"].(string)
		order, _ := args["order"].(string)

		// 数字处理: JSON 数字通常解析为 float64
		var limit int
		if val, ok := args["limit"].(float64); ok {
			limit = int(val)
		} else if val, ok := args["limit"].(int); ok {
			limit = val
		}

		// --- 默认值处理 ---
		if city == "" {
			city = "西安市"
		}
		if sortBy == "" {
			sortBy = "sale_total"
		}
		if order == "" {
			order = "ASC"
		}
		if limit == 0 {
			limit = 10
		}

		// --- 安全检查 ---
		validSorts := map[string]bool{"sale_total": true, "sale_date": true}
		validOrders := map[string]bool{"ASC": true, "DESC": true}
		if !validSorts[sortBy] {
			sortBy = "sale_total"
		}
		if !validOrders[order] {
			order = "ASC"
		}

		// --- SQL 查询 ---
		querySQL := fmt.Sprintf(`
			SELECT store_name, location, sale_total, medicine, city, district
			FROM medicine_sale_summary
			WHERE city = ? AND location != '' AND location IS NOT NULL AND sale_total > 0
			ORDER BY %s %s
			LIMIT ?
		`, sortBy, order)

		rows, err := db.QueryContext(ctx, querySQL, city, limit)
		if err != nil {
			return mcp.NewToolResultError(fmt.Sprintf("Database query error: %v", err)), nil
		}
		defer rows.Close()

		var records []SaleRecord
		for rows.Next() {
			var r SaleRecord
			if err := rows.Scan(&r.StoreName, &r.Location, &r.SaleTotal, &r.Medicine, &r.City, &r.District); err != nil {
				continue
			}
			records = append(records, r)
		}

		toonBytes, err := toon.Marshal(records)
		if err != nil {
			return mcp.NewToolResultError("JSON marshal error"), nil
		}
		log.Print(string(toonBytes))
		return mcp.NewToolResultText(string(toonBytes)), nil
	})

	// 4. 启动服务, 采用流式(Streamable), 也可以使用STDIO(server.ServeStdio)
	return server.NewStreamableHTTPServer(s,
		server.WithHeartbeatInterval(30*time.Second),
		server.WithStateful(true),
	)
}
